import ReactPDF, { Page, View, Document,Text ,Image} from "@react-pdf/renderer";
import {
    ResumePDFSection,
    ResumePDFBulletList,
    ResumePDFText,
} from "components/Resume/ResumePDF/common";
import { styles, spacing } from "components/Resume/ResumePDF/styles";
import { Style as ReactPDFStyle } from "@react-pdf/types";

export const ResumePDFMethod = ({
                                      heading,
                                      method,
                                      themeColor,
                                  }: {
    heading: string;
    method?: {
        type: string;
        elements: Array<{
            elementType: "text" | "image" | "unknown";
            content: string;
            styles: Record<string, number | string>;
        }>;
    };
    themeColor: string;
}) => {
    // 明确声明支持的样式属性列表
    const validStyleKeys: (keyof ReactPDFStyle)[] = [
        'position',
        'top',
        'left',
        'right',
        'bottom',
        'width',
        'height',
        'minWidth',
        'minHeight',
        'maxWidth',
        'maxHeight',
        'margin',
        'marginHorizontal',
        'marginVertical',
        'marginTop',
        'marginBottom',
        'marginLeft',
        'marginRight',
        'padding',
        'paddingHorizontal',
        'paddingVertical',
        'paddingTop',
        'paddingBottom',
        'paddingLeft',
        'paddingRight',
        'flex',
        'flexGrow',
        'flexShrink',
        'flexBasis',
        'flexDirection',
        'flexWrap',
        'backgroundColor',
        'border',
        'borderWidth',
        'borderColor',
        'borderRadius',
        'color',
        'fontSize',
        'fontFamily',
        'fontWeight',
        'fontStyle',
        'textAlign',
        'textDecoration',
        'textTransform',
        'lineHeight',
        'opacity',
        'overflow',
        'alignItems',
        'alignSelf',
        'justifyContent',
        'zIndex'
    ];

    // 类型安全的样式转换函数
    /*const convertStyles = (styles: Record<string, number | string>): ReactPDFStyle => {
        return Object.entries(styles).reduce((acc, [key, value]) => {
            if (validStyleKeys.includes(key as keyof ReactPDFStyle)) {
                const styleKey = key as keyof ReactPDFStyle;

                // 处理数值型属性
                if (typeof value === 'number') {
                    acc[styleKey] = value;
                }
                // 处理字符串型特殊值（如"10pt"）
                else if (typeof value === 'string') {
                    if (/\d+pt$/.test(value)) {
                        acc[styleKey] = parseFloat(value);
                    } else {
                        acc[styleKey] = value;
                    }
                }
            }
            return acc;
        }, {} as ReactPDFStyle);
    };*/
    const convertStyles = (styles: Record<string, number | string>): ReactPDFStyle => {
        return Object.entries(styles).reduce((acc, [key, value]) => {
            // 转换 kebab-case 为 camelCase（如 element-spacing → elementSpacing）
            const camelKey = key.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());

            if (validStyleKeys.includes(camelKey as keyof ReactPDFStyle)) {
                const styleKey = camelKey as keyof ReactPDFStyle;

                // 处理定位属性（自动添加 position: 'absolute'）
                if (['left', 'top', 'right', 'bottom'].includes(camelKey)) {
                    acc.position = 'absolute'; // 👈 自动添加绝对定位
                }

                // 转换所有数字值（无论是否带单位）
                if (typeof value === 'string' && /\d+/.test(value)) {
                    const numericValue = parseFloat(value.replace(/[^\d.]/g, ''));
                    acc[styleKey] = numericValue;
                } else if (typeof value === 'number') {
                    acc[styleKey] = value;
                }
            }
            return acc;
        }, {} as ReactPDFStyle);
    };
    console.log(convertStyles({ 'font-size': '12pt', 'line-height': '1.5' }));

    const renderElement = (
        element: typeof method.elements[number],
        index: number
    ) => {
        console.log("styles:",element.styles)
        const style = convertStyles(element.styles);

        switch (element.elementType) {
            case 'text':
                return (
                    <Text
                        key={`text-${index}`}
                        style={style}
                        wrap // 使用React-PDF官方换行属性
                    >
                        {element.content}
                    </Text>
                );

            case 'image':
                return (
                    <Image
                        key={`img-${index}`}
                        src={element.content}
                        style={{
                            ...style,
                            objectFit: 'cover' as 'cover' // 类型断言
                        }}
                    />
                );

            default:
                return null;
        }
    };

    return (
        <ResumePDFSection themeColor={themeColor} heading={heading}>
            <View style={{ position: 'relative' }}>
                {method?.elements?.map((element, index) =>
                    renderElement(element, index)
                )}
            </View>
        </ResumePDFSection>
    );
};